package com.my.characters;

import java.io.*;

/**
 * @author: marshal
 * @date: 2021-09-27 9:14 PM
 *
 * 字符流IO
 */
public class CharacterIODemo {
    public static void main(String[] args) {
        var path = "file/character_io_demo.txt";
        String data = "This is english.\n这是中文！";
//        testWrite(path, data);

        // 1. 一次读取一个字符
        testRead(path);

    }

    /**
     *  读取数据,一次读取一个字符
     *
     * @param path
     */
    private static void testRead(String path) {
        try (var r = new FileReader(path)) {
            // 一次读取一个字符
            char[] cbuf = new char[1];
            int length = 0;
            while ((length = r.read(cbuf)) > 0) {
                System.out.println(new String(cbuf, 0, length));
            }
            System.out.println("read success.");
        } catch (IOException e) {
            System.out.println("read error => " + e.getMessage());
        }
    }


    /**
     *  写入数据
     *
     * @param path
     * @param data
     */
    private static void testWrite(String path, String data) {
        try (var w = new FileWriter(path)) {
            w.write(data);
            System.out.println("write success.");
        } catch (IOException e) {
            System.out.println("write error => " + e.getMessage());
        }
    }
}
